import React, {useState, useEffect} from 'react';
import { Modal, message, Tag, Button} from 'antd';
import { TagListItem } from '../data';
import { getTagList} from '../service';

interface CreateFormProps {
  modalVisible: boolean;
  topOrgId:number;
  onSubmit: ([]) => void;
  onCancel: () => void;
}

const { CheckableTag } = Tag;

const AssignTagsModel: React.FC<CreateFormProps> = (props) => {
  const { modalVisible, topOrgId, onSubmit, onCancel } = props;
  const [selectedTags, setSelectedTags] = useState([]);
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState<boolean>(false);

  useEffect(() => {
    if(modalVisible){
      setLoading(false);
      const param = new Object();
      param["orgId"] = topOrgId;
      new Promise((resolve, reject) => {
        getTagList(param)
          .then((res) => {
            if (res && res.code === 200) {
              setData(res.data);
              setSelectedTags([]);
              resolve(true);
            } else {
              message.error('请求失败');
              resolve(false);
            }
          })
          .catch((error) => {
            message.error('请求失败');
            reject(error);
          });
      });
    }
  },[modalVisible]);

  const handleUpdate = () =>{
    // if(selectedTags.length >0){
      setLoading(true);
      onSubmit(selectedTags);
    // }else{
    //   message.warn("请选择要分配的标签")
    // }
    
  }

  const handleChange = (tag:TagListItem, checked:boolean) =>{
    const nextSelectedTags = checked ? [...selectedTags, tag.id] : selectedTags.filter(t => t !== tag.id);
    // console.log('You are interested in: ', nextSelectedTags);
    setSelectedTags(nextSelectedTags);
  }

  return (
    <Modal
      destroyOnClose
      width={400}
      title="分配标签"
      visible={modalVisible}
      onCancel={onCancel}
      footer={[
        <>
        <Button type="primary" loading={loading} onClick={handleUpdate}>分配</Button>
        <Button type="default" onClick={onCancel}>返回</Button>
        </>
      ]}

    >
      <ul>
        {data.map((item,index) => 
        <CheckableTag
          key={index} 
          style={{marginBottom:5}}
          checked={selectedTags.indexOf(item.id) > -1}
          className={selectedTags.indexOf(item.id) > -1?"":"ant-tag-blue"}
          onChange={checked => handleChange(item, checked)}>{item.name}
        </CheckableTag>)}
      </ul>
    </Modal>
  );
};

export default AssignTagsModel;
